use strict;
my $prev_idle = 0;
my $prev_total = 0;
my $diff_idle;
my $diff_total;
my $diff_usage;
my $cpu_line;
my @cpu_values;
my $idle;
my $total;
my $i;
my $num = 0;
# Set up the serial port
use Device::SerialPort;
my $port = Device::SerialPort->new("/dev/ttyUSB0");

# 9600, 81N on the USB ftdi driver
$port->baudrate(9600);
$port->databits(8);
$port->parity("none");
$port->stopbits(1);

while(1)
{
  $cpu_line = `cat /proc/stat | grep '^cpu '`;
  @cpu_values = split (/\s+/, $cpu_line);

  $idle = $cpu_values[4];
  $total = 0;
  for($i = 1;$i < $#cpu_values; $i++)
  {
    #print("$cpu_values[$i]\n");
    $total = $total + $cpu_values[$i];
  }

  $diff_idle = $idle - $prev_idle;
  $diff_total = $total - $prev_total;
  $diff_usage = (1000 * ($diff_total - $diff_idle) / $diff_total + 5) / 10;
  
  $diff_usage = sprintf "%.0f", $diff_usage;

  print("$diff_usage\n");
  $port->write(chr($diff_usage));
  #$port->write(chr($num));
  #$num = $num + 10;
  #if ($num >= 100)
  #{
  #	$num = 0;
  #}

  $prev_total = $total;
  $prev_idle = $idle;
#sleep(1);
  select(undef, undef, undef, 0.2);
}
